package com.jtpay.sdk.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.jtpay.sdk.R;
import com.jtpay.sdk.adapter.BaseRecycleAdapter;
import com.jtpay.sdk.adapter.ChannelAdapter;
import com.jtpay.sdk.base.BaseActivity;
import com.jtpay.sdk.util.AuthUtil;
import com.jtpay.sdk.util.PayUtilHelper;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import apiUtils.apis.GetChannelsAPI;
import apiUtils.apis.SwitchChannelAPI;
import apiUtils.models.ChannelModel;
import apiUtils.models.OrderModel;
import apiUtils.models.PayInfo;
import apiUtils.models.PayTypeModel;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;
import sdk.pay.model.TokenParam;
import sdk.pay.utils.PayMD5Util;

/**
 * Created by Administrator on 2017/8/22.
 */

public class SwitchChannelActivity extends BaseActivity implements PayUtilHelper.Observer, BaseRecycleAdapter.OnSelectItemListener, TextWatcher {
    @Bind(R.id.payType_textView)
    TextView mPayTypeTextView;
    @Bind(R.id.layout_title_textName)
    TextView mTitleTextView;
    @Bind(R.id.current_channel_TextView)
    TextView mCurrentChannelTextView;
    @Bind(R.id.switch_channel_EditText)
    EditText mChannelEditText;
    @Bind(R.id.switch_channel_RecycleView)
    RecyclerView mChannelRecyclerView;

    private PayTypeModel mTypeModel;
    private ChannelAdapter mAdapter = new ChannelAdapter();
    private List<ChannelModel> mModels = new ArrayList<>();
    private OrderModel mOrderModel;

    @Override
    protected void initView() {
        mTitleTextView.setText(R.string.switch_channel);
        if (mTypeModel != null) {
            mCurrentChannelTextView.setText(mTypeModel.getUsingChannelName());
            mPayTypeTextView.setText(mTypeModel.getProductTypeName());
        }
        mChannelRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mChannelRecyclerView.setAdapter(mAdapter);
        mChannelEditText.addTextChangedListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismisProgress();
        finish();
    }

    @Override
    protected void initData() {
        PayUtilHelper.getInstance().attachObserver(this);
        Intent intent = getIntent();
        mTypeModel = intent.getParcelableExtra("data");
        mOrderModel = intent.getParcelableExtra("oreder");
        initRecycleViewData();
        mAdapter.setData(mModels);
        mAdapter.setListener(this);
    }

    private void initRecycleViewData() {
        showProgress(R.string.get_channel_loading);
        new GetChannelsAPI().getChannels(mTypeModel.getProductTypeCode(), mTypeModel.getTypeCode(),
                PayInfo.getInstance().getAppId(), new GetChannelsAPI.Listener() {
                    @Override
                    public void onSuccess(List<ChannelModel> models) {
                        dismisProgress();
                        if (models == null || models.isEmpty()) {
                            return;
                        }
                        mModels.clear();
                        mModels.addAll(models);
                        mAdapter.setData(mModels);
                    }

                    @Override
                    public void onFailure(int code, String message) {
                        dismisProgress();
                        ToastUtil.showShort(R.string.get_channel_error);
                    }
                });
    }

    @Override
    protected int setView() {
        return R.layout.activity_switch_channel;
    }

    @OnClick({R.id.swithc_channel_pay_Button, R.id.exit_View, R.id.layout_title_iv_left})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.swithc_channel_pay_Button:
                switchChannelAndPayAction();
                break;
            case R.id.exit_View:
                AuthUtil.getInstance().logOut();
                break;
            case R.id.layout_title_iv_left:
                finish();
                break;
            default:

                break;
        }
    }

    private void switchChannelAndPayAction() {
        final ChannelModel model = mAdapter.getSelecteData();
        if (model == null) {
            ToastUtil.showShort(R.string.please_select_switch_channel);
            return;
        }
        showProgress(R.string.loading);
        new SwitchChannelAPI().switchChannel(mTypeModel.getProductTypeCode(), model.getChannelCode(), mTypeModel.getTypeCode(),
                PayInfo.getInstance().getAppId(), new SwitchChannelAPI.Listener() {
                    @Override
                    public void onSuccess(String message) {
                        setResult(RESULT_OK);
                        PayInfo.getInstance().setPayTypeName(mTypeModel.getProductTypeName());
                        PayInfo.getInstance().setChannelName(model.getChannelName());
                        PayUtilHelper.getInstance().pay(mTypeModel.getProductTypeCode(), getTokenParam(mTypeModel.getProductTypeCode()));
                    }

                    @Override
                    public void onFailure(int code, String message) {
                        dismisProgress();
                        ToastUtil.showShort(R.string.switch_channel_error);
                    }
                });
    }

    @Override
    public void onChangeCallBack() {
        dismisProgress();
    }

    private TokenParam getTokenParam(String code) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String app_key = PayInfo.getInstance().getAppKey();
        String p1_appid = PayInfo.getInstance().getAppId();
        String p2_order = mOrderModel.getOrderNumber();
        String p3_money = mOrderModel.getOrderMoney();
        String p6_ordertime = dateFormat.format(date);
        String p8_sign = PayMD5Util.getMD5(
                p1_appid + "&" + p2_order + "&" + p3_money + "&"
                        + p6_ordertime + "&" + code + "&" + app_key);
        TokenParam tokenParam = new TokenParam();
        tokenParam.setP1_appid(p1_appid);
        tokenParam.setP2_orderNumber(p2_order);
        tokenParam.setP3_money(p3_money);
        tokenParam.setP6_orderTime(p6_ordertime);
        tokenParam.setP7_productCode(code);
        tokenParam.setP8_sign(p8_sign);
        return tokenParam;
    }

    @Override
    public void selectItem(int position) {
        Log.e("test", "position = " + position);
        if (position != -1)
            mChannelEditText.setText(mAdapter.getSelecteData().getChannelName());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mAdapter.getFilter().filter(s);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
